﻿using System.Windows.Controls;

namespace SHomeWorkshop.LunarPresentation.Commands
{
    public partial class Command
    {
        /// <summary>
        /// 插入预定义结构的网格式。
        /// </summary>
        private static Expressions.Grid InsertCustomGrid(string gridXmlText)
        {
            if (Globals.selectedEditor == null) return null;
            if (Globals.selectedEditor.SelectedExpression == null)
            {
                System.Windows.MessageBox.Show("请先选择一个公式作为插入新公式的基准位置！",
                    Globals.appName, System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Warning);
                return null;
            }

            LunarPresentation.Expressions.Expression curEx
                = Globals.selectedEditor.SelectedExpression;

            if (curEx is Expressions.SubPanel)
            {
                System.Windows.MessageBox.Show("不能在子面板后面插入新公式，请选择其它位置！",
                    Globals.appName, System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Warning);
                return null;
            }

            if (curEx.Parent is StackPanel)
            {
                ModifingItem mi = new ModifingItem();

                curEx.XmlData.InsertXml(gridXmlText);

                StackPanel spanel = curEx.Parent as StackPanel;
                LunarPresentation.Expressions.Grid newExpression =
                    new LunarPresentation.Expressions.Grid(curEx.RootPanel, curEx.ParentPanel, curEx.Editor);
                spanel.Children.Insert(spanel.Children.IndexOf(curEx) + 1, newExpression);
                newExpression.XmlData = Globals.selectedEditor.SelectedExpression.XmlData.NextSibling;

                Action action = new Action(newExpression.ExID, spanel.Children.IndexOf(newExpression),
                    newExpression.GetType().Name, "InsertExpression", null, gridXmlText, ActionType.Insert,
                    newExpression.ParentPanel.ExID);

                Action actionIndent = new Action(newExpression.ExID, spanel.Children.IndexOf(newExpression),
                    newExpression.GetType().Name, "Indent", newExpression.Indent.ToString(), curEx.Indent.ToString());

                newExpression.Indent = curEx.Indent;// 插入新公式时自动同步缩进。                

                mi.Add(action);
                mi.Add(actionIndent);

                newExpression.Editor.Do(mi);

                Globals.selectedEditor.SelectedExpression = newExpression;
                Globals.selectedEditor.IsModified = true;

                return newExpression;
            }

            return null;
        }

        // Row已不再由网格式模拟实现。此方法已移动到“InsertExpression.cs”中。2010年12月25日
        ///// <summary>
        ///// 插入行。
        ///// </summary>
        //public static bool InsertRow()
        //{
        //    //Expressions.Grid grid = InsertCustomGrid(LunarPresentation.Properties.Resources.Row);
        //    //return grid == null ? false : true;
        //}
    }
}
